//CREATE TABLE 'users'('id' INTEGER PRIMARY KEY AUTOINCREMENT,'username' VARCHAR(105) NOT NULL,'password' VARCHAR(105) NOT NULL);
//CREATE TABLE 'tokens'('id' INTEGER PRIMARY KEY NOT NULL,'token' VARCHAR(305) PRIMARY KEY NOT NULL);
//CREATE TABLE 'notes'('id' INTEGER PRIMARY KEY AUTOINCREMENT,'ownerid' INTEGER NOT NULL,'title' TINYTEXT,'updatetime' TINYTEXT,'content' TEXT);

const sqlite3=require('sqlite3')
const config=require('../../config')


let db=new sqlite3.Database(config.server.database.datafile)

module.exports={
    GetAByBInT:(T,A,B)=>new Promise((resolve,reject)=>{
        let pairsB=[]
        for(key in B){
            pairsB.push(`${key}=${(typeof B[key]=='string')?`'${B[key]}'`:B[key]}`)
        }
        if(pairsB.length==0){
            pairsB.push('TRUE')
        }
        if(A.length==0){
            A.push('*')
        }
        db.all(
            `SELECT ${A.join()} FROM ${T} WHERE ${pairsB.join(' AND ')};`,(err,result)=>{
                if(err){
                    reject(err)
                }else{
                    resolve(result)
                }
            })
    }),
    InsertAInT:(T,A)=>new Promise((resolve,reject)=>{
        db.run(
            `INSERT INTO ${T} (${Object.keys(A).join()}) VALUES (${Object.values(A).map((v)=>(((typeof v)=='string')?`'${v}'`:v)).join()});`,(err)=>{
                if(err){
                    reject(err)
                }else{
                    resolve()
                }
            }
        )
    }),
    DeleteAInT:(T,A)=>new Promise((resolve,reject)=>{
        let pairs=[]
        for(key in A){
            pairs.push(`${key}=${(typeof A[key]=='string')?`'${A[key]}'`:A[key]}`)
        }
        db.run(
            `DELETE FROM ${T} WHERE ${pairs.join(' AND ')};`,(err)=>{
                if(err){
                    reject(err)
                }else{
                    resolve()
                }
            }
        )
    }),
    UpdateAToBInT:(T,A,B)=>new Promise((resolve,reject)=>{
        let pairsA=[],
            pairsB=[]
        for(key in A){
            pairsA.push(`${key}=${(typeof A[key]=='string')?`'${A[key]}'`:A[key]}`)
        }
        for(key in B){
            pairsB.push(`${key}=${(typeof B[key]=='string')?`'${B[key]}'`:B[key]}`)
        }
        db.run(
            `UPDATE ${T} SET ${pairsB.join()} WHERE ${pairsA.join(' AND ')};`,(err)=>{
                if(err){
                    reject(err)
                }else{
                    resolve()
                }
            }
        )
    })
}